package com.boot.cluster.utils;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;

public class NetworkUtils {

//	public static String clientIp(HttpServletRequest request) {
//		String ipAddress = request.getHeader("x-forwarded-for");
//		if ((ipAddress == null) || (ipAddress.length() == 0)
//				|| "unknown".equalsIgnoreCase(ipAddress)) {
//			ipAddress = request.getHeader("Proxy-Client-IP");
//		}
//		if ((ipAddress == null) || (ipAddress.length() == 0)
//				|| "unknown".equalsIgnoreCase(ipAddress)) {
//			ipAddress = request.getHeader("WL-Proxy-Client-IP");
//		}
//		if ((ipAddress == null) || (ipAddress.length() == 0)
//				|| "unknown".equalsIgnoreCase(ipAddress)) {
//			ipAddress = request.getRemoteAddr();
//			if ("127.0.0.1".equals(ipAddress)|| "0:0:0:0:0:0:0:1".equals(ipAddress)) {
//				//根据网卡取本机配置的IP
//				InetAddress inet = null;
//				try {
//					inet = InetAddress.getLocalHost();
//					ipAddress = inet.getHostAddress();
//				} catch (final UnknownHostException e) {
//					e.printStackTrace();
//				}
//			}
//
//		}
//		//对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
//		if ((ipAddress != null) && (ipAddress.length() > 15)&&(ipAddress.indexOf(',') > 0)) {
//			ipAddress = ipAddress.substring(0, ipAddress.indexOf(','));
//		}
//		return ipAddress;
//	}


    public static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf("windows") > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    public static String localIP() {
        String sIP = "";
        InetAddress ip = null;
        try {
            if (NetworkUtils.isWindowsOS()) {
                ip = InetAddress.getLocalHost();
            } else {
                boolean bFindIP = false;
                Enumeration<NetworkInterface> nf = NetworkInterface.getNetworkInterfaces();
                while (nf.hasMoreElements()) {
                    if (bFindIP) {
                        break;
                    }
                    NetworkInterface ni = nf.nextElement();
                    if (ni.isVirtual() || ni.isLoopback() || ni.isUp() || ni.isPointToPoint()) {
                        continue;
                    }
                    Enumeration<InetAddress> ips = ni.getInetAddresses();
                    while (ips.hasMoreElements()) {
                        ip = ips.nextElement();
                        if (ip.isSiteLocalAddress()
                                && !ip.isLoopbackAddress() // 127.开头的都是lookback地址
                                && (ip.getHostAddress().indexOf(":") == -1) && !ip.getHostAddress().startsWith("172")) {
                            bFindIP = true;
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }


    public static String getHttpPort() {
        MBeanServer mBeanServer = null;
        if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
            mBeanServer = MBeanServerFactory.findMBeanServer(null).get(0);
        }
        Set<ObjectName> names = null;
        try {
            if (mBeanServer != null) {
                names = mBeanServer.queryNames(new ObjectName("Catalina:type=Connector,*"), null);
            }
            if ((names != null) && (mBeanServer != null)) {
                Iterator<ObjectName> it = names.iterator();
                ObjectName oname;
                String port = "";
                while (it.hasNext()) {
                    oname = it.next();
                    String pvalue = (String) mBeanServer.getAttribute(oname, "protocol");
                    String svalue = (String) mBeanServer.getAttribute(oname, "scheme");
                    if ("http".equals(svalue)) {
                        if (pvalue.contains("http11")) {
                            return ((Integer) mBeanServer.getAttribute(oname, "port")).toString();
                        } else if (pvalue.startsWith("HTTP")) {
                            port = ((Integer) mBeanServer.getAttribute(oname, "port")).toString();
                        }
                    }
                }
                return port;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return "";
    }

}
